package cn.actoncode.boot.module.ai.socket.chat;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/api/socket/chat/{sk}")
public class ChatSocket {

    private static ConcurrentHashMap<Long, Session> sessionMap = new ConcurrentHashMap<>();

    private Session session;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session, @PathParam("sk") Long sk) {
        this.session = session;
        sessionMap.put(sk, session);
        log.info("[chat]socketKey:{}", sk + "-->建立连接");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("sk") Long sk) {
        sessionMap.remove(sk);
        log.info("[chat]socketKey:{}", sk + "-->断开连接");
    }

    @OnError
    public void onError(Session session, Throwable t, @PathParam("sk") Long sk) {
        log.info("[chat]socketKey:{} \n ErrorMsg:{}", sk, t.getMessage());
    }

    public void sendMessage(Session session, String message) {
        if (null != session && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                log.info(e.getMessage());
            }
        }
    }

    public void sendMessage(Long sk, String message) {
        Session session1 = sessionMap.get(sk);
        sendMessage(session1, message);
    }
}
